<template>
  <div>
    <div class="basicSet" ref="childBasic">
      <affix :label="$t('configLazyLoad.channel.dockingBasic')">
        <el-form ref="form" :model="form" :label-position="'left'"  label-width="160px">
          <el-form-item :label="$t('configLazyLoad.channel.webName')">
            <el-input v-model.trim="form.name" size="mini"></el-input>
          </el-form-item>
          <el-form-item :label="$t('configLazyLoad.channel.webUrl')">
            <el-input v-model.trim="form.webDomain" :placeholder="$t('configLazyLoad.channel.inputWebUrl')" size="mini"></el-input>
          </el-form-item>
          <el-form-item :label="$t('configLazyLoad.channel.webTitle')" style="position: relative;">
            <el-input v-model.trim="form.pageTitle" placeholder="www.7moor.com" size="mini"></el-input>
            <el-tooltip class="item" effect="dark" :content="$t('configLazyLoad.channel.webTitleTip')" placement="bottom">
              <span class="iconfont icon-tixingweizhi"></span>
            </el-tooltip>
          </el-form-item>
          <el-form-item :label="$t('configLazyLoad.channel.useSche')">
            <el-radio-group v-model.trim="form.scheduleEnable">
              <el-radio :label="false">{{$t('config.channel.notEnabled')}}</el-radio>
              <el-radio :label="true">{{$t('sms.reuse')}}</el-radio>
            </el-radio-group>
            <div><span class="prompt">{{$t('configLazyLoad.channel.scheTip')}}</span></div>
          </el-form-item>
          <chooseSkillCroup v-show="!form.scheduleEnable" :toPeerInfo="form.ToPeer"></chooseSkillCroup>
          <el-form-item v-show="!form.scheduleEnable" :label="$t('configLazyLoad.channel.enableRobot')">
            <el-select v-model="form.robot" @visible-change="robotSelectShow">
              <el-option value="">{{$t('public.pleasePick')}}</el-option>
              <el-option
                v-for="item in robotConfig"
                :key="item._id"
                :label="item.robot_name_new"
                :disabled="item.disabled"
                :value="item._id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('configLazyLoad.channel.enableRobotAgent')" v-if="!form.scheduleEnable && aiRobots.length > 0">
            <el-select v-model="form.robotAssistId" @visible-change="robotSelectShow">
              <el-option value="">{{$t('public.pleasePick')}}</el-option>
              <el-option
                v-for="item in aiRobots"
                :key="item._id"
                :label="item.robot_name_new"
                :disabled="item.disabled"
                :value="item._id"
              >
              </el-option>
            </el-select>
            <div><span class="prompt">{{$t('configLazyLoad.channel.robotTip')}}</span></div>
          </el-form-item>
          <el-form-item :label="$t('configLazyLoad.channel.enableSatis')">
            <el-radio-group v-model="form.webchat_csr">
              <el-radio :label="false">{{$t('config.channel.notEnabled')}}</el-radio>
              <el-radio :label="true">{{$t('sms.reuse')}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.userBehaviorReplay" :label="$t('configLazyLoad.channel.enableReplay')">
            <el-radio-group v-model="form.userBehaviorReplay">
              <el-radio :label="false">{{$t('config.channel.notEnabled')}}</el-radio>
              <el-radio :label="true">{{$t('sms.reuse')}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </affix>
      <affix :label="$t('configLazyLoad.channel.conversationConfig')">
        <el-form ref="form" :model="form" :label-position="'left'"  label-width="160px">
        <el-form-item :label="$t('configLazyLoad.channel.mode')">
          <div>
            <el-radio v-model="form.autoShowInviteType" :label="'1'">{{$t('configLazyLoad.channel.direcTalk')}}</el-radio>
          </div>
          <p class="help-tips font12">{{$t('configLazyLoad.channel.robotTip2')}}</p>
          <div>
            <el-radio v-model="form.autoShowInviteType" :label="'2'">{{$t('configLazyLoad.channel.inviteConfirm')}}</el-radio>
            <span class="setInviteStyle font12" @click="setInviteStyle">{{$t('configLazyLoad.channel.setStyle')}}</span>
          </div>
          <p class="help-tips font12">{{$t('configLazyLoad.channel.robotTip2')}}</p>
        </el-form-item>
        <el-form-item :label="$t('configLazyLoad.channel.enableAutoPop')">
          <el-radio-group v-model.trim="form.autoInvite">
            <el-radio :label="'0'">{{$t('config.channel.notEnabled')}}</el-radio>
            <el-radio :label="'1'">{{$t('sms.reuse')}}</el-radio>
          </el-radio-group>
          <div class="sourse_cur font12" v-show="form.autoInvite === '1'">
            <span>{{$t('configLazyLoad.channel.openStop')}}</span>
            <el-input size="mini" class="inviteInput" v-model.trim="form.openStayTime" type="number" min="0" @blur="timeBlur"></el-input>
            <span>{{$t('configLazyLoad.channel.pop1')}}</span>
          </div>
          <div class="sourse_cur font12" v-show="form.autoInvite === '1'">
            <span>{{$t('configLazyLoad.channel.pop2')}}</span>
            <el-input size="mini" class="inviteInput" v-model.trim="form.closeStayTime" type="number" min="0" @blur="timeBlur"></el-input>
            <span>{{$t('configLazyLoad.channel.pop3')}}</span>
          </div>
        </el-form-item>
        </el-form>
      </affix>
      <affix :label="$t('configLazyLoad.channel.chooseTalkMode')">
        <div>
          <p class="change_win">
            <el-radio v-model="changeWindow" :label="'pure'">{{$t('configLazyLoad.channel.pureVer')}}</el-radio>
            <a href="javascript:;" @click="editWinStyle('pure')">{{$t('configLazyLoad.channel.setPopStyle')}}</a>
          </p>
          <p class="change_win">
            <el-radio v-model="changeWindow" :label="'common'">{{$t('configLazyLoad.channel.commonVer')}}</el-radio>
            <a href="javascript:;" @click="editWinStyle('common')">{{$t('configLazyLoad.channel.setPopStyle')}}</a>
          </p>
        </div>
      </affix>
      <div class="save_config">
        <el-button type="primary" @click="saveConfig(form)" class="primary_btn">{{$t('config.channel.saveSettings')}}</el-button>
      </div>
    </div>
    <!--<styleConfig v-if="isEditWinStyle" @tellSave="tellSave" :styleData="basicData" ref="childStyle"></styleConfig>-->
  </div>
</template>
<script>
  import {deepClone} from '@/utils/m7Utils.js'
  import chooseSkillCroup from '../../base/chooseSkillGroup'
  import Affix from '@/components/ui-modules/affix/Affix'
  import styleConfig from './styleConfig'
  export default {
    name: 'ChannelSkillGroup',
    data () {
      return {
        dialogVisible: false,
        isEdit: [true],
        value: '',
        form: {
          webDomain: '',
          name: '',
          pageTitle: '',
          robot: '',
          webchat_csr: true,
          ToPeer: [],
          userBehaviorReplay: false,
          autoInvite: '0',
          openStayTime: '10',
          closeStayTime: '10',
          robotType: '',
          webchat_showTypeName: true,
          autoShowInviteType: '1',
          scheduleEnable: false,
          robotAssistId: ''
        },
        // 初始化列表用，相当于重置
        intiForm: {
          webDomain: '',
          name: '',
          pageTitle: this.$t('configLazyLoad.channel.consultAgent'),
          robot: '',
          webchat_csr: true,
          ToPeer: [],
          userBehaviorReplay: false,
          autoShowInviteType: '1',
          autoInvite: '0',
          openStayTime: '10',
          closeStayTime: '10',
          robotType: '',
          webchat_showTypeName: true,
          scheduleEnable: false
        },
        changeWindow: 'pure',
        options: [],
        dealSkill: {
          id: '',
          name: '',
          status: 'enable'
        },
        robotConfig: [],
        aiRobots: [],
        isEditWinStyle: false
      }
    },
    components: {
      chooseSkillCroup,
      styleConfig,
      Affix
    },
    props: {
      basicData: {
        type: Object,
        default: function () {
          return {}
        }
      }
    },
    watch: {
      basicData: {
        handler: function (val) {
          this.inti(deepClone(val))
        },
        deep: true
      },
      changeWindow (cur) {
        this.$emit('changeWin', {changeWindow: this.changeWindow})
      }
    },
    methods: {
      saveConfig (data) {
        if (!data.name) {
          this.$emit('backTop')
          this.$message.error(this.$t('configLazyLoad.channel.inputSiteName'))
          return
        }
        if (!data.scheduleEnable) {
          if (data.ToPeer.length === 0) {
            this.$emit('backTop')
            this.$message.error(this.$t('webchat.placeSkillsGrouop'))
            return
          }
          let skillStatus = false
          data.ToPeer.map((item) => {
            if (item.status === 'enable') {
              skillStatus = true
            }
          })
          if (!skillStatus) {
            this.$message.error(this.$t('configLazyLoad.channel.AtLeastOne'))
            return
          }
          this.robotConfig.map((item) => {
            if (data.robot === item._id) {
              if (item.Nick) {
                data.robotType = '7mbot_ai'
              } else {
                data.robotType = item.robot_type_new
              }
            }
          })
        }
        data.openStayTime = '' + parseInt(data.openStayTime)
        data.closeStayTime = '' + parseInt(data.closeStayTime)
        console.log(data)
        this.$emit('saveConfig', data)
      },
      // 初始化基本设置信息
      inti (val) {
        if (JSON.stringify(val) === '{}') {
          this.changeWindow = 'pure'
          this.form = deepClone(this.intiForm)
        } else {
          for (let i in this.form) {
            this.form[i] = val[i] === undefined ? this.intiForm[i] : val[i]
          }
          if (val.advConfig) {
            this.changeWindow = val.advConfig.windowType || 'pure'
          } else {
            this.changeWindow = 'pure'
          }
          // this.form.webDomain = ''
//          this.form.openStayTime = '10'
//          this.form.closeStayTime = '10'
          this.form._id = val._id === undefined ? '' : val._id
          this.form.accessId = val.accessId === undefined ? '' : val.accessId
        }
      },
      // 失去焦点判断输入是否符合
      timeBlur () {
        if (this.form.openStayTime <= 0 && this.form.openStayTime !== '0') {
          this.$message.error(this.$t('configLazyLoad.channel.robotError1'))
          this.form.openStayTime = '0'
        }
        if (this.form.closeStayTime <= 0 && this.form.closeStayTime !== '0') {
          this.$message.error(this.$t('configLazyLoad.channel.robotError1'))
          this.form.closeStayTime = '0'
        }
      },
      // 编辑技能组，渲染dialog，记录编辑技能组列表的索引，通过this.isEdit[0]判断添加技能组还是编辑
      editSkill (index) {
        this.dialogVisible = true
        this.dealSkill.id = this.form.ToPeer[index].id
        this.dealSkill.name = this.form.ToPeer[index].name
        this.dealSkill.status = this.form.ToPeer[index].status
        this.isEdit[0] = false
        this.isEdit[1] = index
      },
      // 编辑技能组状态
      editStatus (index) {
        this.form.ToPeer[index].status = this.form.ToPeer[index].status === 'disable' ? 'enable' : 'disable'
      },
      // 添加技能组，初始化dialog
      addGroup () {
        this.dialogVisible = true
        this.dealSkill.id = ''
        this.dealSkill.name = ''
        this.dealSkill.status = 'enable'
      },
      // 确定添加技能组
      confirmAdd () {
        if (!this.dealSkill.id) {
          this.$emit('backTop')
          this.$message.error(this.$t('webchat.placeSkillsGrouop'))
          return
        } else if (!this.dealSkill.name) {
          this.$emit('backTop')
          this.$message.error(this.$t('configLazyLoad.channel.robotError2'))
          return
        }
        if (this.isEdit[0]) {
          let isDef = true
          this.form.ToPeer.map(item => {
            if (item.id === this.dealSkill.id) {
              this.$emit('backTop')
              this.$message.error(this.$t('configLazyLoad.channel.robotError3'))
              isDef = false
            }
          })
          if (!isDef) {
            return
          }
          isDef && this.form.ToPeer.push(deepClone(this.dealSkill))
        } else {
          let skill = this.form.ToPeer[this.isEdit[1]]
          skill.id = this.dealSkill.id
          skill.name = this.dealSkill.name
          skill.status = this.dealSkill.status
          this.isEdit[0] = true
        }
        this.dialogVisible = false
      },
      // 选择技能组的触发，目的使技能组和类型名称相同
      choseSkill () {
        var _this = this
        var typeName = this.options.filter(function (item, index) {
          return item.value === _this.dealSkill.id
        })
        if (typeName[0].value) {
          this.dealSkill.name = typeName[0].label
        }
      },
      // 删除技能组
      delSkill (index) {
        this.form.ToPeer.splice(index, 1)
      },
      editWinStyle (type) {
        this.changeWindow = type
        this.isEditWinStyle = true
        this.$emit('editStyle', {isEditWinStyle: this.isEditWinStyle, changeWindow: this.changeWindow, scheduleEnable: this.form.scheduleEnable})
      },
      setInviteStyle () {
        this.$emit('editInviteStyle')
      },
      robotSelectShow (show) {
        if (show) {
          this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
            if (res2 && res2.success && res2.data && res2.data.length > 0) {
              let aiRobot = res2.data
              let allRobot = this.robotConfig
              aiRobot.forEach((item1) => {
                item1._id = item1.Id
                item1.robot_name_new = item1.Nick
                let exist = allRobot.findIndex((all) => {
                  return all.Id === item1.Id
                })
                if (exist === undefined) {
                  allRobot.push(item1)
                } else {
                  allRobot.splice(exist, 1, item1)
                }
              })
              this.aiRobots = aiRobot
              this.robotConfig = allRobot
            }
          })
        }
      }
    },
    // 获取机器人和技能组列表
    beforeMount () {
      this.inti(deepClone(this.basicData))
      this.$store.dispatch('getDicCache', {type: 'mailQueues'}).then((res) => {
        if (res.data.length <= 0) {
          this.$message(this.$t('configLazyLoad.channel.robotError4'))
          return
        }
        res.data.map((item, index) => {
          this.options.push({
            label: item.DisplayName,
            value: item.Exten
          })
        })
        this.options.unshift({
          label: this.$t('public.pleasePick1'),
          value: ''
        })
      })
      this.$store.dispatch('getCache', {type: 'robotConfig'}).then((res) => {
        if (res) {
          this.robotConfig = res
        }
        this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
          if (res2 && res2.success && res2.data && res2.data.length > 0) {
            let aiRobot = res2.data
            aiRobot.forEach((item1) => {
              item1._id = item1.Id
              item1.robot_name_new = item1.Nick
            })
            this.aiRobots = aiRobot
            this.robotConfig = this.robotConfig.concat(this.aiRobots)
            console.log(this.robotConfig)
          }
        })
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../../assets/common.styl"
  .basicSet
    height calc(100vh - 266px)
    overflow auto
    padding 20px 20px 40px 20px
    .save_config
      text-align center
      .el-button
        min-width 90px
    .iconfont
      display inline-block
      width 16px
      height 16px
      border 1px solid $c-main
      border-radius 50%
      font-size 10px
      color $c-main
      text-align center
      line-height 16px
      margin-left 6px
      position: absolute
      top: 10px
    .el-form
      width: 60%
    .change_win
      width: 100%;
      line-height: 30px;
      a
        margin-left 20px
    .inviteInput
      display: inline-block;
      width: 60px;
      margin: 0 10px;
      height: 24px;
    .help-tips
      color $cf-gray4
      padding-left 20px
    .setInviteStyle
      color $c-main
      cursor pointer
      margin 0 10px
  .prompt
    color $c-prompt
    line-height 2
    font-size 12px
</style>
